package com.xudow.app.ui;

import android.app.Application;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

import com.xudow.app.Config;
import com.xudow.app.R;
import com.xudow.app.XApplication;
import com.xudow.app.db.DatabaseHelper;
import com.xudow.app.db.dao.MessageDao;
import com.xudow.app.model.LocalMessage;
import com.xudow.app.ui.adapter.MessageAdapter;
import com.xudow.app.ui.support.RecyclerViewScrollLocationListener;
import com.xudow.app.ui.support.XLinearLayoutManager;
import com.xudow.app.ui.task.MessageListTask;
import com.xudow.app.util.Maps;
import com.xudow.app.util.PrefUtils;
import com.xudow.app.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 普通消息Fragment
 *
 * @author lukecheng
 */
public class MessageFragment extends BaseFragment
        implements MessageAdapter.OnRecyclerViewListener {

    private List<LocalMessage> messages;
    private MessageAdapter messageAdapter;

    private RecyclerView orderRecyclerView;
    private ProgressBar progressBar;
    private LinearLayout contentView;

    private MessageListTask messageListTask;

    private int page = 1;  //当前页数

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_message_list, container, false);

        orderRecyclerView = (RecyclerView) v.findViewById(R.id.order_list);
        orderRecyclerView.setHasFixedSize(true);

        XLinearLayoutManager layoutManager = new XLinearLayoutManager(getActivity());
        layoutManager.setOnRecyclerViewScrollLocationListener(orderRecyclerView,
                new RecyclerViewScrollLocationListener() {
                    @Override
                    public void onTopWhenScrollIdle(RecyclerView recyclerView) {
                    }

                    @Override
                    public void onBottomWhenScrollIdle(RecyclerView recyclerView) {
                        if (null == messages || messages.size() < 1) {
                            return;
                        }

                        LocalMessage msg = messages.get(messages.size() - 1);
                        XApplication application = (XApplication) getActivity().getApplication();

                        loadMessagesFromDB(application.getUserProfileId(), msg.getCreateTime());

                        messageAdapter.notifyDataSetChanged();
                    }
                });
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        orderRecyclerView.setLayoutManager(layoutManager);

        progressBar = (ProgressBar) v.findViewById(R.id.progressbar);
        contentView = (LinearLayout) v.findViewById(R.id.content);

        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        messages = new ArrayList<LocalMessage>();

        messageAdapter = new MessageAdapter(getActivity(), messages);
        messageAdapter.setOnRecyclerViewListener(this);
        orderRecyclerView.setAdapter(messageAdapter);

        XApplication application = (XApplication) getActivity().getApplication();

        if (application.isLogin()) {
            loadMessagesFromDB(application.getUserProfileId(), null);
        }

        loadMessages();
    }

    @Override
    public void onItemClick(int position) {
        LocalMessage msg = messages.get(position);

        if (msg.getIsSystemMessage() == 1) {
            //系统消息
            Intent intent = new Intent(getActivity(), MessageViewActivity.class);
            intent.putExtra("messageId", msg.getMessageId());
            startActivity(intent);
        } else {
            //平文消息
            Intent intent = new Intent(getActivity(), TextMessageViewActivity.class);
            intent.putExtra("messageId", msg.getMessageId());
            intent.putExtra("content", msg.getContent());
            startActivity(intent);
        }
    }

    @Override
    public boolean onItemLongClick(int position) {
        return false;
    }

    /**
     * 获取Message Handler
     */
    private Handler messageListTaskHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideLoadingDialog();
            if (msg.what == MessageListTask.SUCCESS) {
                onCourseListSuccess(msg.getData());
            }
        }
    };

    private void onCourseListSuccess(Bundle data) {
        com.activeshare.edu.ucenter.models.msg.Message[] messageArr =
                (com.activeshare.edu.ucenter.models.msg.Message[]) data.getSerializable("messages");

        if (null != messageArr && messageArr.length > 0) {
            saveMessage(messageArr);
        }

        if (getActivity() == null) {
            return;
        }

        PrefUtils.saveMessageTimeStamp(getActivity(),
                PrefUtils.getHomeMessageTimeStamp(getActivity()));
    }

    private void loadMessages() {
        HashMap<String, String> params = Maps.newHashMap();
        String timestamp = PrefUtils.getMessageTimeStamp(getActivity());

        XApplication application = (XApplication) getActivity().getApplication();

        if (!StringUtils.isEmpty(timestamp) && application.isLogin()) {
            params.put("timestamp", PrefUtils.getMessageTimeStamp(getActivity()));
        }

        messageListTask = new MessageListTask(getActivity(), messageListTaskHandler);
        messageListTask.execute(params);
        showLodingDialog("正在加载");
    }

    /**
     * 从db加载消息
     *
     * @param userId
     */
    private void loadMessagesFromDB(long userId, Date startTime) {
        DatabaseHelper databaseHelper = new DatabaseHelper(getActivity());
        SQLiteDatabase db = databaseHelper.getReadableDatabase();

        MessageDao messageDao = new MessageDao(db);
        List<LocalMessage> messagesInDB = messageDao.getMessages(userId, false, startTime);

        db.close();

        messages.addAll(messagesInDB);

        messageAdapter.notifyDataSetChanged();
    }

    /**
     * 保存消息到db
     *
     * @param messageList
     */
    private void saveMessage(com.activeshare.edu.ucenter.models.msg.Message[] messageList) {
        if (null == getActivity()) {
            return;
        }

        XApplication application = (XApplication) getActivity().getApplication();

        DatabaseHelper databaseHelper = new DatabaseHelper(getActivity());
        SQLiteDatabase db = databaseHelper.getWritableDatabase();

        List<LocalMessage> tmpMsgs = new ArrayList<LocalMessage>();

        MessageDao messageDao = new MessageDao(db);

        for (com.activeshare.edu.ucenter.models.msg.Message msg : messageList) {
            LocalMessage localMessage = new LocalMessage();
            localMessage.setMessageId(msg.getId());
            localMessage.setUserId(application.getUserProfileId());
            localMessage.setChannel(Config.MSG_CHANNEL_MESSAGE);

            if (1 == msg.getIsSystemMessage()) {
                localMessage.setContent(msg.getSubhead());
                localMessage.setIsSystemMessage(msg.getIsSystemMessage());
            } else {
                localMessage.setContent(msg.getContent());
                //系统消息接口 isSystemMessage 1的是系统消息，0的是oa消息
                localMessage.setIsSystemMessage(LocalMessage.MSG_TYPE_OA);
            }

            localMessage.setCreateTime(msg.getCreateTime());

            localMessage.setMessageId(msg.getId());
            localMessage.setStatus(msg.getStatus());
            localMessage.setTitle(msg.getTitle());
            localMessage.setUserId(application.getUserProfileId());

            tmpMsgs.add(localMessage);

            messageDao.insertMessage(localMessage);
        }

        db.close();

        //重新加载message
        messages.clear();

        if (application.isLogin()) {
            loadMessagesFromDB(application.getUserProfileId(), null);
        } else {
            messages.addAll(tmpMsgs);
            messageAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onDestroy() {
        if (null != messageListTask && !messageListTask.isCancelled()) {
            messageListTask.cancel(true);
            messageListTask = null;
        }

        super.onDestroy();
    }

}